package org.pblue.tumblarity.service;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pblue.appengine.AppengineDataManager;
import org.pblue.tumblarity.data.bean.Tumblelog;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

/**
 * This is a cron scheduled service mapped to /admin/fetch.
 * 
 * @author mikolaj
 *
 */
public class FetchAllService extends HttpServlet {

  private static final long serialVersionUID = 1L;
  
  public static final String QUEUE_FETCH_TUMBLELOG = "fetchtumblelog-queue";
  public static final String QUEUE_FETCH_PAGE = "fetchpage-queue";
  public static final String QUEUE_COMPARE = "compare-queue";
  
  public static final String PARAM_TUMBLELOG_ID = "tumblelogId";
  public static final String PARAM_PAGE = "page";
  public static final String PARAM_RETRY = "retry";
  
  @SuppressWarnings("unchecked")
  @Override
  protected void service(HttpServletRequest pReq, HttpServletResponse pRes) throws ServletException, IOException {
    Queue fetchTumblelogQueue = QueueFactory.getQueue(FetchAllService.QUEUE_FETCH_TUMBLELOG);
    
    // get all tumblelog ids with 'idle' fetch state and a retry count below the limit
    PersistenceManager pm = AppengineDataManager.getPersistenceManager();
    Query query = pm.newQuery("select id from " + Tumblelog.class.getName());
    List<String> ids = (List<String>) query.execute();
    
    // queue a task for each tumblelog id to fetch that tumblelog
    for (String id : ids) {
      fetchTumblelogQueue.add(TaskOptions.Builder.withUrl("/task/fetchtumblelog").param(FetchAllService.PARAM_TUMBLELOG_ID, id));
    }
  }
  
}
